// JScript source code
/*FigList.js*/
/*Get a list of figures from a document or set of documents*/
Main();

function fileList(folderspec)
{
	var fso, f, f1, fc, s;
	fso = new ActiveXObject("Scripting.FileSystemObject");
	f = fso.GetFolder(folderspec);
	fc = new Enumerator(f.files);
	s = "";
	for (; !fc.atEnd(); fc.moveNext())
	{
		s += fc.item().name + ",";
	}
	
	//take care of the comma as the last character
	s = s.slice(0, s.length - 1);
	return(s);
}

function Main()
{
	var arrFiles, strFileName;
	var xmlDocOut = new ActiveXObject("Msxml2.DOMDocument.3.0");
	
	strFileName = "Z:\\Documents\\EleList.xml";
	
	arrFiles = fileList("../xml").split(",");
	
	var xmlDocOut = new ActiveXObject("Msxml2.DOMDocument.3.0");
	
	//Create the list of Elements
	eleList = xmlDocOut.createElement("elementManifest");
	
	for(i = 0; i < arrFiles.length; i++)
	{
		WScript.Echo("Processing item " + (i + 1) + " of " + arrFiles.length);
		eleList.appendChild(getEleList(arrFiles[i], "//note"));
	}
	
	pi = xmlDocOut.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
	xmlDocOut.loadXML(pi.xml + '<?xml-stylesheet href="EleList.xsl" type="text/XSL"?>' 
		+ eleList.xml);
	
	/*Debug*/
	WScript.Echo(xmlDocOut.xml);

	xmlDocOut.save(strFileName);
}

/*
Function: getFigList
Input:
	strXmlDoc: the path to the xml document
Output:
	getEleList: the xml figure list
*/
function getEleList(strXmlDoc, strEleSelect)
{
	var strFigEntry;
	var eleIdno;
	var eleList;
	var xmlDocIn = new ActiveXObject("Msxml2.DOMDocument.3.0");
	var xmlDocOut = new ActiveXObject("Msxml2.DOMDocument.3.0");
	xmlDocIn.load("../xml/" + strXmlDoc);
	if (xmlDocIn.parseError.errorCode != 0) 
	{
		var myErr = xmlDocIn.parseError;
		WScript.Echo("You have error " + myErr.reason);
	} 
	else 
	{
		eleList = xmlDocOut.createElement("eleList");
		
		/*Debug*/
		WScript.Echo(eleList.xml);

		xmlDocIn.setProperty("SelectionLanguage", "XPath");
		
		//write the figure element
		objNodeList = xmlDocIn.documentElement.selectNodes(strEleSelect);	
		
		if(objNodeList.length > 0)
		{	
			
			//Write the id of the entry
			eleIdno = xmlDocOut.createElement("idno");
			eleIdno.text = strXmlDoc;
			eleList.appendChild(eleIdno);
		}
		
		for (var i = 0; i < objNodeList.length; i++)
		{
			eleList.appendChild(objNodeList.item(i));
		}

		/*Debug*/
		WScript.Echo(eleFigList.xml);
		return eleList;
	}

}